<template>
    <div>
        <el-row>
            <el-col :span="3">
              <el-button type="primary" :icon="CirclePlusFilled" @click="addData.dialog = true">新增用户</el-button>
              <el-dialog :append-to-body="true" draggable v-model="addData.dialog" title="新增用户" width="35%">
                <el-form :model="addData" label-width="70px">
                <el-form-item label="用户名称">
                    <el-input v-model="addData.username"/>
                </el-form-item>
                    <el-form-item  label="用户头像">
                        <el-upload
                        class="avatar-uploader"
                        action="http://localhost:3030/user/upload/avatar/"
                        :headers="myHeaders"
                        :show-file-list="false"
                        :on-success="addAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                        >
                        <img :src="addData.photo" class="avatar" />
                        </el-upload>
                </el-form-item>
                <el-form-item label="联系方式">
                    <el-input v-model="addData.phone"/>
                </el-form-item>
                <el-form-item label="用户角色">
                    <el-select v-model="addData.role" placeholder="用户角色">
                    <el-option v-for="item in role_types" 
                        :label="item.name"
                        :key="item.permission" :value="item.permission"
                    />
                    </el-select>
                </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="addData.dialog = false">关闭</el-button>
                        <el-button type="primary" @click="addUser">添加</el-button>
                    </span>
                </template>
            </el-dialog>
            </el-col>
            <el-col :span="10">
                <el-select v-model="searchCondition.role" placeholder="选择用户角色">
                    <el-option v-for="item in role_types" 
                        :label="item.name"
                        :key="item.permission" :value="item.permission"
                    />
                    <el-option label="全部" value="all">全部</el-option>
                </el-select>
                <el-button  type="info" :icon="Search" style="margin-left: 3%;" @click="getUserByRole">搜索</el-button>
            </el-col>
            <el-col :span="4" :offset="5">
                <el-input :suffix-icon="Opportunity" v-model="searchCondition.username" placeholder="请输入名称"></el-input>
            </el-col>
            <el-col :span="2">
                <el-button  type="success" :icon="Search" style="margin-left: 8%;" @click="getUserByLike">搜索</el-button>
            </el-col>
        </el-row>
        <el-table border stripe :data="users" height="479px" style="width: 100%;margin-top: 10px;" 
            :header-cell-style="{'background':'#b1b3b8','text-align':'center','color':'white'}"
            :cell-style="{'text-align':'center'}" @selection-change="handleUserSelect">
            <el-table-column type="selection" width="60" /> 
            <el-table-column prop="username" label="用户名称" width="100"/>
            <el-table-column label="用户头像" width="100">
                <template #default="scope">
                    <el-image :src="scope.row.photo" style="width: 50px; height: 50px;border-radius: 50%;" />
                </template>
            </el-table-column>
            <el-table-column prop="phone" label="联系方式" width="150"/>
            <el-table-column label="角色" width="100">
                <template #default="scope"> 
                    <el-tag :type="scope.row.tag">{{scope.row.roleName}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="标识" width="130">
                <template #default="scope"> 
                    <el-tag effect="dark" :type="scope.row.tag">{{scope.row.role}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="状态" width="180" sortable sort-by="status">
                <template #default="scope">
                    <el-switch
                        v-model="scope.row.status"
                        @change="changeStatus(scope.row)"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                        active-text="正常"
                        inactive-text="禁用"
                    />
                </template>
            </el-table-column>
            <el-table-column prop="loginTime" label="最近登录时间" width="200" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="warning"  :icon="Edit" @click="EditUser(scope.row)">编辑</el-button>
                    <el-dialog :append-to-body="true" draggable v-model="scope.row.Editdialog" title="用户编辑" width="35%">
                        <el-form :model="editUser" label-width="70px">
                        <el-form-item label="用户名称">
                            <el-input v-model="editUser.username"/>
                        </el-form-item>
                            <el-form-item  label="用户头像">
                                <el-upload
                                class="avatar-uploader"
                                action="http://localhost:3030/user/upload/avatar/"
                                :headers="myHeaders"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload"
                                >
                                 <img :src="editUser.photo" class="avatar" />
                                </el-upload>
                        </el-form-item>
                        <el-form-item label="联系方式">
                            <el-input v-model="editUser.phone"/>
                        </el-form-item>
                        <el-form-item label="用户角色">
                            <el-select v-model="editUser.role" placeholder="用户角色">
                            <el-option v-for="item in role_types" 
                                :label="item.name"
                                :key="item.permission" :value="item.permission"
                            />
                            </el-select>
                        </el-form-item>
                        </el-form>
                        <template #footer>
                            <span class="dialog-footer">
                                <el-button @click="scope.row.Editdialog = false">关闭</el-button>
                                <el-button type="primary" @click="updateUser(scope.row)">修改</el-button>
                            </span>
                        </template>
                    </el-dialog>
                    <el-popconfirm
                        width="220"
                        confirm-button-text="确认"
                        cancel-button-text="我再想想"
                        cancel-button-type="info"
                        :icon="InfoFilled"
                        icon-color="red"
                        title="你确定删除吗?"
                        @confirm="deleteUser(scope.row)"
                        >
                        <template #reference>
                            <el-button type="danger" :icon="Delete">删除</el-button>
                        </template>
                 </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-row style="margin-top: 20px;">
            <el-col :span="10">
                <el-tag type="success" style="height: 32px; vertical-align: middle;font-size: 17px;">
                    已选择 <span style="color: #79bbff;margin-right: 5px;">{{selected_count}}</span>条记录
                  </el-tag>
                  <el-button type="danger" :icon="DeleteFilled" @click="bulk_deletion" plain style="margin-left: 15px;">批量删除</el-button>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="12">
              <div class="demo-pagination-block" style="float: right;">
                <el-pagination
                  v-model:current-page="currentPage"
                  :page-size="6"
                  :total="total"
                  :background="true"
                  layout="prev, pager, next"
                  @current-change="handleCurrentChange"
                />
              </div>
            </el-col>
          </el-row>
    </div>
</template>
<script>
    import request from '@/utils/request'
    import {useStore} from 'vuex';
    import {ref,reactive} from 'vue'
    import {Edit,Delete,CirclePlusFilled,InfoFilled,DeleteFilled,
            Search,Opportunity} from '@element-plus/icons-vue'
    import { ElMessageBox,ElMessage,ElNotification} from 'element-plus'
    import {respTousers} from '@/assets/js/common'
    export default{
        name:'SystemUser',
        setup() {
            let users = ref([])
            const store = useStore()
            const icon = {Edit,Delete,CirclePlusFilled,InfoFilled,DeleteFilled,Search,Opportunity}
            let selected_count = ref(0)
            let deleteSelect = ref([]) //批量删除的用户id集合
            let searchCondition = reactive({
                username:'',
                role:'',
            })
            let editUser = ref({})
            let addData = reactive({
                username:'',phone:'',
                role:'',dialog:false,
                photo:'https://cdn.acwing.com/media/user/profile/photo/110905_lg_e9b844238f.jpg',
            })
            let role_types = ref([])
            let currentPage = ref(1)
            let total = ref(6)
            const myHeaders = ref({
              Authorization:"Bearer "+store.state.user.token
            })
            let EditUser = (user) => {
                user.Editdialog = true
                editUser.value = user
            }
            const handleCurrentChange = (page) => {
                currentPage.value = page;
                getUsers()
            } 
            //批量删除
            let bulk_deletion = () => {
                if(selected_count.value != 0){
                    request({
                        url:'/user/bulkDelete/',
                        method:'post',
                        data:{
                            role:store.state.user.role,
                            select:JSON.stringify(deleteSelect.value)
                        },
                        headers:{
                            Authorization:"Bearer "+store.state.user.token,
                        },
                        }).then((resp)=>{
                        if(resp.message === 'success'){
                            getUsers()
                            ElMessage({message: '删除成功!',type: 'success'})
                            deleteSelect.value = []
                            }else if(resp.message === 'error'){
                                ElMessage({message: '没有权限!',grouping: true,type: 'error'})
                            }
                        }).catch(() => {
                        });
                }else{
                    ElMessage({message: '请勾选删除的选项!',grouping: true,type: 'warning'})
                }
            }
            //选择的用户集合
            const handleUserSelect= function(selected){
                selected_count.value = selected.length
                for(const user of selected) {
                    deleteSelect.value.push(user.id)
                }
            }
            let getUserByRole = () => {
                if(searchCondition.role === 'all'){
                    getUsers()
                }else{
                    request({
                        url:"/user/get/byRole/",
                        method:"get",
                        params:{
                            role:searchCondition.role,
                            operateRole:store.state.user.role,
                        },
                        headers:{
                            Authorization:"Bearer "+store.state.user.token,
                        }
                    }).then((resp) => {
                        if(resp.message === 'success'){
                            users.value = respTousers(resp).users;
                        }else{
                            ElMessage({message: '没有权限',type: 'error'})
                        }
                    }).catch(() => {});
                }
            }
            let getUserByLike = () => {
                request({
                    url:'/user/get/byName/',
                    method:'get',
                    params:{
                        role:store.state.user.role,
                        username:searchCondition.username
                    },
                    headers:{
                        Authorization:"Bearer "+store.state.user.token,
                    }
                }).then((resp) => {
                    let userData = respTousers(resp)
                    users.value = userData.users 
                }).catch(() => {});
            }
            let getRoleType = () => {
                request({
                    url:'/role/getAll/',
                    method:'get',
                    params:{
                        role:store.state.user.role
                    },
                    headers:{
                        Authorization:"Bearer "+store.state.user.token,
                    }
                }).then((resp) => {
                    role_types.value = resp;
                })
            }
            getRoleType()
            let getUsers = () => {
                request({
                    url:'/user/get/',
                    method:'get',
                    params:{
                        role:store.state.user.role,
                        page:currentPage.value
                    },
                    headers:{
                        Authorization:"Bearer "+store.state.user.token,
                    }
                }).then((resp) => {
                    if(resp.message === 'success'){
                        users.value = respTousers(resp).users;
                        total.value = resp.total;
                    }
                })
            }
            getUsers()
            let updateUserStatus = (user) => {
                request({
                    url:'/user/update/status/',
                    method:"get",
                    params:{
                        id:user.id,
                        status:user.status,
                        role:store.state.user.role
                    },
                    headers:{
                        Authorization:"Bearer "+store.state.user.token,
                    }
                }).then((resp) => {
                    if(resp.message === 'success'){
                        ElNotification({
                            title: 'Success',
                            message: user.username+'状态更新成功',
                            type: 'success',
                        })
                    }else{
                        ElMessage({message: '没有权限',type: 'error'})
                    }
                    getUsers()
                }).catch(() => {
                    ElMessage({message: '修改失败!',type: 'error'})
                })
            }
            //改变用户状态
            let changeStatus = (row) => {
                if(!row.status){
                    ElMessageBox.confirm(
                        '确定禁用该用户吗?',
                        'Warning',
                        {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning',
                        }
                    ).then(() => {
                        updateUserStatus(row)
                    }).catch(() => {
                        row.status = true
                    })
                }else{
                    updateUserStatus(row)
                }
            }
            let addUser = () => {
                request({
                    url:'/user/add/',
                    method:'post',
                    data:{
                        operateRole:store.state.user.role,
                        ...addData,
                    },
                    headers:{
                        Authorization:"Bearer "+store.state.user.token,
                    }
                }).then((resp) => {
                    if(resp.message === 'success'){
                        getUsers();
                        ElMessage({message: '添加成功',type: 'success'})
                    }else if(resp.message === 'repeat'){
                        ElMessage({message: '用户名重复',type: 'error'})
                    }else{
                        ElMessage({message: '没有权限',type: 'error'})
                    }
                    addData.dialog = false;
                }).catch(() => {})
            }
            let updateUser = (user) => {
                request({
                    url:'/user/update/',
                    method:'post',
                    data:{
                        role:store.state.user.role,
                        id:user.id,
                        username:user.username,
                        photo:user.photo,
                        phone:user.phone,
                        userRole:user.role
                    },
                    headers:{
                        Authorization:"Bearer "+store.state.user.token,
                    }
                }).then((resp) => {
                    if(resp.message === 'success'){
                        ElMessage({message: '修改成功',type: 'success'})
                    }else if(resp.message === 'repeat'){
                        ElMessage({message: '用户名重复',type: 'error'})
                    }else{
                        ElMessage({message: '没有权限',type: 'error'})
                    }
                    getUsers();
                }).catch(() => {})
            }
            //上传头像
            const addAvatarSuccess = (resp) => {
                addData.photo = 'http://localhost:3030' + resp.avatarUrl;
            }
            const handleAvatarSuccess = (resp) => {
                editUser.value.photo = "http://localhost:3030" + resp.avatarUrl;
            }
            const beforeAvatarUpload = () =>{
            }
            let deleteUser = (user) => {
                request({
                    url:'/user/delete/',
                    method:'post',
                    data:{
                        id:user.id,
                        role:store.state.user.role
                    },
                    headers:{
                        Authorization:"Bearer "+store.state.user.token,
                    }
                }).then((resp) => {
                    if(resp.message === 'success'){
                        getUsers()
                        ElMessage({message: '删除成功',type: 'success'})
                    }else{
                        ElMessage({message: '没有权限',type: 'error'})
                    }
                }).catch(() => {})
            }
            return {
                ...icon,
                users,
                editUser,
                addData,
                currentPage,
                total,
                role_types,
                myHeaders,
                selected_count,
                handleCurrentChange,
                deleteSelect,
                handleUserSelect,
                getUserByRole,
                getUserByLike,
                bulk_deletion,
                searchCondition,
                changeStatus,
                updateUser,
                deleteUser,
                EditUser,
                addUser,
                handleAvatarSuccess,
                addAvatarSuccess,
                beforeAvatarUpload,
            }
        },
    }
</script>
<style scoped> 
.avatar-uploader .avatar {
  width: 80px;
  height: 80px;
  display: block;
}
</style>